<template>
  <div class="order-alert-container">
    <!-- 顶部标题 -->
    <div class="header-title">
    </div>

    <!-- 左右两个图表面板 -->
    <div class="charts-container">
      <!-- 左侧：下一卷 -->
      <div class="chart-panel left-panel">
        <div class="panel-header">
          <div class="coil-info">
            <span class="coil-number">酸轧厚度预警</span>
          </div>
          <div class="unit-label">mm</div>
        </div>
        
        <!-- 筛选条件区域 -->
        <div class="filter-section">
          <div class="filter-item">
            <span class="filter-label">入口卷号</span>
            <el-input
              v-model="filterParams.entryCoilNo"
              placeholder="请输入"
              clearable
              size="small"
              class="filter-input"
            />
          </div>
          <div class="filter-item">
            <span class="filter-label">厚度</span>
            <el-select
              v-model="filterParams.thickness"
              placeholder="请选择"
              clearable
              size="small"
              class="filter-select"
            >
              <el-option
                v-for="item in thicknessOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="filter-label">宽度</span>
            <el-select
              v-model="filterParams.width"
              placeholder="请选择"
              clearable
              size="small"
              class="filter-select"
            >
              <el-option
                v-for="item in widthOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="filter-label">客户名称</span>
            <el-select
              v-model="filterParams.customerCode"
              placeholder="请选择"
              clearable
              size="small"
              class="filter-select"
            >
              <el-option
                v-for="item in customerCodeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="filter-label">钢种</span>
            <el-select
              v-model="filterParams.steelGrade"
              placeholder="请选择或输入搜索"
              clearable
              filterable
              size="small"
              class="filter-select"
            >
              <el-option
                v-for="item in steelGradeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="filter-label">开始时间</span>
            <el-date-picker
              v-model="filterParams.startTime"
              type="datetime"
              placeholder="选择开始时间"
              size="small"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="filter-input"
              clearable
            />
          </div>
          <div class="filter-item">
            <span class="filter-label">结束时间</span>
            <el-date-picker
              v-model="filterParams.endTime"
              type="datetime"
              placeholder="选择结束时间"
              size="small"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="filter-input"
              clearable
            />
          </div>
          <!-- <div class="filter-item">
            <span class="filter-label">厚度设定值</span>
            <el-select
              v-model="filterParams.thicknessSetting"
              placeholder="请选择"
              clearable
              size="small"
              class="filter-select"
            >
              <el-option
                v-for="item in thicknessSettingOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div> -->
          <div class="filter-item">
            <el-button
              type="primary"
              size="small"
              @click="handleQuery"
              :loading="queryLoading"
              class="query-btn"
            >
              查询
            </el-button>
          </div>
        </div>

        <div class="chart-wrapper">
          <div ref="nextCoilChartRef" class="chart"></div>
          <!-- <div class="threshold-label">
            <span class="threshold-text">{{ nextCoilNo }}上限: {{ nextCoilUpperline }}</span><span class="arrow">→</span><span class="threshold-text">下限: {{ nextCoilThreshold }}</span>
            
          </div> -->
        </div>
      </div>

      <!-- 第二行：连退 + 镀锌 -->
      <div class="bottom-charts">
        <!-- 连退 -->
        <div class="chart-panel left-panel">
          <div class="panel-header">
            <div class="coil-info">
              <span class="coil-number">连退厚度预警</span>
            </div>
            <div class="unit-label">mm</div>
          </div>
          
          <!-- 连退筛选条件区域 -->
          <div class="filter-section filter-section-single-row">
            <div class="filter-item">
              <span class="filter-label">入口卷号</span>
              <el-input
                v-model="continuousRefundFilterParams.entryCoilNo"
                placeholder="请输入"
                clearable
                size="small"
                class="filter-input"
              />
            </div>
            <div class="filter-item">
              <span class="filter-label">厚度</span>
              <el-input
                v-model="continuousRefundFilterParams.thickness"
                placeholder="请输入"
                clearable
                size="small"
                style="width:70px"
                class="filter-input"
              />
            </div>
            <div class="filter-item">
              <span class="filter-label">钢种</span>
              <el-select
                v-model="continuousRefundFilterParams.steelGrade"
                placeholder="请选择或输入搜索"
                clearable
                filterable
                size="small"
                style="width:90px"
                class="filter-select"
              >
                <el-option
                  v-for="item in continuousRefundSteelGradeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="filter-item">
              <span class="filter-label">时间</span>
              <el-date-picker
                v-model="continuousRefundFilterParams.startTime"
                type="datetime"
                placeholder="选择开始时间"
                size="small"
                style="width:150px"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="filter-input"
                clearable
              />
            </div>
            <div class="filter-item">
              <span class="filter-label">-</span>
              <el-date-picker
                v-model="continuousRefundFilterParams.endTime"
                type="datetime"
                placeholder="选择结束时间"
                size="small"
                style="width:150px"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="filter-input"
                clearable
              />
            </div>
            <div class="filter-item">
              <el-button
                type="primary"
                size="small"
                @click="handleContinuousRefundQuery"
                :loading="continuousRefundQueryLoading"
                class="query-btn"
              >
                查询
              </el-button>
            </div>
          </div>
          <!-- 减薄量显示 -->
          <div class="thinning-display">
            <span class="thinning-label">减薄量：</span>
            <span class="thinning-value">{{ continuousRefundThinning !== null ? continuousRefundThinning.toFixed(3) : '-' }} mm</span>
          </div>
          
          <div class="chart-wrapper">
            <div ref="continuousRefundChartRef" class="chart"></div>
          </div>
        </div>
        <!-- 镀锌 -->
        <div class="chart-panel right-panel">
          <div class="panel-header">
            <div class="coil-info">
              <span class="coil-number">镀锌厚度预警</span>
            </div>
            <div class="unit-label">mm</div>
          </div>
          
          <!-- 镀锌筛选条件区域 -->
          <div class="filter-section filter-section-single-row">
            <div class="filter-item">
              <span class="filter-label">入口卷号</span>
              <el-input
                v-model="galvanizingFilterParams.entryCoilNo"
                placeholder="请输入"
                clearable
                size="small"
                class="filter-input"
              />
            </div>
            <div class="filter-item">
              <span class="filter-label">厚度</span>
              <el-input
                v-model="galvanizingFilterParams.thickness"
                placeholder="请输入"
                clearable
                size="small"
                style="width:70px"
                class="filter-input"
              />
            </div>
            <div class="filter-item">
              <span class="filter-label">钢种</span>
              <el-select
                v-model="galvanizingFilterParams.steelGrade"
                placeholder="请选择或输入搜索"
                clearable
                filterable
                size="small"
                style="width:90px"
                class="filter-select"
              >
                <el-option
                  v-for="item in galvanizingSteelGradeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="filter-item">
              <span class="filter-label">时间</span>
              <el-date-picker
                v-model="galvanizingFilterParams.startTime"
                type="datetime"
                placeholder="选择开始时间"
                size="small"
                style="width:150px"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="filter-input"
                clearable
              />
            </div>
            <div class="filter-item">
              <span class="filter-label">-</span>
              <el-date-picker
                v-model="galvanizingFilterParams.endTime"
                type="datetime"
                placeholder="选择结束时间"
                size="small"
                style="width:150px"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="filter-input"
                clearable
              />
            </div>
            <div class="filter-item">
              <el-button
                type="primary"
                size="small"
                @click="handleGalvanizingQuery"
                :loading="galvanizingQueryLoading"
                class="query-btn"
              >
                查询
              </el-button>
            </div>
          </div>
          <!-- 减薄量显示 -->
          <div class="thinning-display">
            <span class="thinning-label">减薄量：</span>
            <span class="thinning-value">{{ galvanizingThinning !== null ? galvanizingThinning.toFixed(3) : '-' }} mm</span>
          </div>
          
          <div class="chart-wrapper">
            <div ref="galvanizingChartRef" class="chart"></div>
          </div>
        </div>
      </div>



      <!-- 右侧：当前卷 -->
      <!-- <div class="chart-panel right-panel">
        <div class="panel-header">
          <div class="coil-info">
            <span class="coil-number">当前卷{{ currentCoilNo }} 切边</span>
          </div>
          <div class="unit-label">mm</div>
        </div>
        <div class="chart-wrapper">
          <div ref="currentCoilChartRef" class="chart"></div>
          <div class="threshold-label">
            <span class="threshold-text">{{ currentCoilNo }}下限: {{ currentCoilThreshold }}</span>
          </div>
        </div>
      </div> -->
    </div>

    <!-- 点击蓝点弹窗：当前卷曲线与中位线/上下限 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`出口卷号：${dialogCoilNo || '-'}`"
      width="70%"
      destroy-on-close
      append-to-body
      @open="onDialogOpen"
      @closed="onDialogClosed"
      class="thk-dialog"
    >
      <div class="dialog-chart-wrapper">
        <div ref="dialogChartRef" class="chart"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { thicknessAndLayOutJudgeApi } from '/@/api/thicknessAndLayOutJudge/index';
import { historyApi } from '/@/api/furnaceTempDynamicCtrl/history';

// 数据
const weldDistance = ref(249.46);
const voiceAlarmEnabled = ref(false);
const nextCoilNo = ref('5AB3H5740000');
const currentCoilNo = ref('5BB302180000');
const nextCoilThreshold = ref<number[]>([]);
const currentCoilThreshold = ref(1525);

// 筛选参数 - 酸轧
const filterParams = ref({
  entryCoilNo: '',
  thickness: '',
  width: '',
  customerCode: '',
  steelGrade: '',
  thicknessSetting: '',
  startTime: '',
  endTime: '',
});

// 筛选参数 - 连退
const continuousRefundFilterParams = ref({
  entryCoilNo: '',
  thickness: '',
  steelGrade: '',
  startTime: '',
  endTime: '',
});

// 筛选参数 - 镀锌
const galvanizingFilterParams = ref({
  entryCoilNo: '',
  thickness: '',
  steelGrade: '',
  startTime: '',
  endTime: '',
});

// 查询加载状态
const queryLoading = ref(false);
const continuousRefundQueryLoading = ref(false);
const galvanizingQueryLoading = ref(false);

// 下拉框选项类型
interface SelectOption {
  label: string;
  value: string;
}

// 厚度选项
const thicknessOptions = ref<SelectOption[]>([]);

// 宽度选项
const widthOptions = ref<SelectOption[]>([]);

// 客户编码选项
const customerCodeOptions = ref<SelectOption[]>([]);

// 钢种选项
const steelGradeOptions = ref<SelectOption[]>([]);

// 连退钢种选项
const continuousRefundSteelGradeOptions = ref<SelectOption[]>([
  { label: '440W', value: '440W' },
  { label: 'B170P', value: 'B170P' },
  { label: 'B210P', value: 'B210P' },
  { label: 'B250P', value: 'B250P' },
  { label: 'B260P2', value: 'B260P2' },
  { label: 'BH340', value: 'BH340' },
  { label: 'BZT2', value: 'BZT2' },
  { label: 'CR210', value: 'CR210' },
  { label: 'CR270', value: 'CR270' },
  { label: 'CR300', value: 'CR300' },
  { label: 'CR340', value: 'CR340' },
  { label: 'CR380', value: 'CR380' },
  { label: 'CR420', value: 'CR420' },
  { label: 'DC01', value: 'DC01' },
  { label: 'DC01-2', value: 'DC01-2' },
  { label: 'DC01-H', value: 'DC01-H' },
  { label: 'DC01-TD', value: 'DC01-TD' },
  { label: 'DC03', value: 'DC03' },
  { label: 'DC04', value: 'DC04' },
  { label: 'DC04-L', value: 'DC04-L' },
  { label: 'DC05', value: 'DC05' },
  { label: 'DC06', value: 'DC06' },
  { label: 'DC07', value: 'DC07' },
  { label: 'DP440', value: 'DP440' },
  { label: 'DP590-1', value: 'DP590-1' },
  { label: 'DP590-2', value: 'DP590-2' },
  { label: 'DP590-3', value: 'DP590-3' },
  { label: 'DP590-D', value: 'DP590-D' },
  { label: 'GQ11', value: 'GQ11' },
  { label: 'GQ12', value: 'GQ12' },
  { label: 'GQ221', value: 'GQ221' },
  { label: 'GQ241', value: 'GQ241' },
  { label: 'GQ391', value: 'GQ391' },
  { label: 'GQ393', value: 'GQ393' },
  { label: 'GQ397', value: 'GQ397' },
  { label: 'GQ481', value: 'GQ481' },
  { label: 'GQ493', value: 'GQ493' },
  { label: 'GQ495', value: 'GQ495' },
  { label: 'GQ562', value: 'GQ562' },
  { label: 'HC260LA-S2', value: 'HC260LA-S2' },
  { label: 'HC260Y', value: 'HC260Y' },
  { label: 'HC340LA-S', value: 'HC340LA-S' },
  { label: 'HC380LA-S1', value: 'HC380LA-S1' },
  { label: 'HC420LA-L', value: 'HC420LA-L' },
  { label: 'HC420LA-S', value: 'HC420LA-S' },
  { label: 'HC420LA-Y', value: 'HC420LA-Y' },
  { label: 'HC460LA', value: 'HC460LA' },
  { label: 'HC500LA', value: 'HC500LA' },
  { label: 'SAE1010', value: 'SAE1010' },
  { label: 'SECC-H', value: 'SECC-H' },
  { label: 'SPCC', value: 'SPCC' },
  { label: 'SPCC-SD', value: 'SPCC-SD' },
  { label: 'SPCC-TS', value: 'SPCC-TS' },
  { label: 'St37', value: 'St37' },
  { label: 'TR590', value: 'TR590' },
]);

// 镀锌钢种选项
const galvanizingSteelGradeOptions = ref<SelectOption[]>([
  { label: '440WD+Z', value: '440WD+Z' },
  { label: '590RD+Z', value: '590RD+Z' },
  { label: '590TRD+Z', value: '590TRD+Z' },
  { label: 'AUX-51D', value: 'AUX-51D' },
  { label: 'AUX-52D', value: 'AUX-52D' },
  { label: 'AUX-53D', value: 'AUX-53D' },
  { label: 'B240P1D+Z', value: 'B240P1D+Z' },
  { label: 'CR210LA', value: 'CR210LA' },
  { label: 'CR420LA+Z', value: 'CR420LA+Z' },
  { label: 'DC51D+Z', value: 'DC51D+Z' },
  { label: 'DC51D-BYD', value: 'DC51D-BYD' },
  { label: 'DC52D+Z', value: 'DC52D+Z' },
  { label: 'DC53D+Z', value: 'DC53D+Z' },
  { label: 'DC54D+Z', value: 'DC54D+Z' },
  { label: 'DC56D+Z', value: 'DC56D+Z' },
  { label: 'DC57D+Z', value: 'DC57D+Z' },
  { label: 'DH590+Z', value: 'DH590+Z' },
  { label: 'DH780+Z-Al', value: 'DH780+Z-Al' },
  { label: 'DP450+Z', value: 'DP450+Z' },
  { label: 'GQ411', value: 'GQ411' },
  { label: 'GQ60', value: 'GQ60' },
  { label: 'GQ941', value: 'GQ941' },
  { label: 'H180BD+Z', value: 'H180BD+Z' },
  { label: 'H180YD+Z', value: 'H180YD+Z' },
  { label: 'H220BD+Z', value: 'H220BD+Z' },
  { label: 'H220YD+Z', value: 'H220YD+Z' },
  { label: 'H260LAD+Z', value: 'H260LAD+Z' },
  { label: 'H260YD+Z', value: 'H260YD+Z' },
  { label: 'H300LAD+Z', value: 'H300LAD+Z' },
  { label: 'H340LAD+Z', value: 'H340LAD+Z' },
  { label: 'H380LAD+Z', value: 'H380LAD+Z' },
  { label: 'H420LAD+Z', value: 'H420LAD+Z' },
  { label: 'H420LAV+Z', value: 'H420LAV+Z' },
  { label: 'HC260LAD-S2', value: 'HC260LAD-S2' },
  { label: 'HC420LAD-S', value: 'HC420LAD-S' },
  { label: 'SGCC', value: 'SGCC' },
]);

// 厚度设定值选项
const thicknessSettingOptions = ref<SelectOption[]>([]);

// 图表引用
const nextCoilChartRef = ref<HTMLElement | null>(null);
const currentCoilChartRef = ref<HTMLElement | null>(null);
let nextCoilChartInstance: echarts.ECharts | null = null;
let currentCoilChartInstance: echarts.ECharts | null = null;
const dialogChartRef = ref<HTMLElement | null>(null);
let dialogChartInstance: echarts.ECharts | null = null;

// 连退/镀锌 图表引用
const continuousRefundChartRef = ref<HTMLElement | null>(null);
let continuousRefundChartInstance: echarts.ECharts | null = null;
const galvanizingChartRef = ref<HTMLElement | null>(null);
let galvanizingChartInstance: echarts.ECharts | null = null;

// 下一卷数据
const nextCoilXData = ref<number[]>([]);
const nextCoilYData = ref<number[]>([]);

// 下一卷上下限与中线
const nextCoilMidline = ref<number[]>([]); // 中线 = exthkSet
const nextCoilUpperline = ref<number[]>([]); // 上限 = exthkSet * 1.1

// 当前卷数据
const currentCoilXData = ref<number[]>([]);
const currentCoilYData = ref<number[]>([]);
// 实时厚度平均值
const currentThkData = ref<number[]>([]);

// 连退数据
const continuousRefundXData = ref<number[]>([]);
const continuousRefundYData = ref<number[]>([]);
const continuousRefundMidline = ref<Array<number | null>>([]);
const continuousRefundUpperline = ref<Array<number | null>>([]);
const continuousRefundThreshold = ref<Array<number | null>>([]);

// 镀锌数据
const galvanizingXData = ref<number[]>([]);
const galvanizingYData = ref<number[]>([]);
const galvanizingMidline = ref<Array<number | null>>([]);
const galvanizingUpperline = ref<Array<number | null>>([]);
const galvanizingThreshold = ref<Array<number | null>>([]);

// 减薄量
const continuousRefundThinning = ref<number | null>(null);
const galvanizingThinning = ref<number | null>(null);

// 点击映射：将蓝色点索引映射到所在卷段
interface CoilSegment {
  coilNo: string;
  extid: string | number | null;
  startIndex: number;
  endIndex: number;
  exThkMin: number | null;
  exThkMax: number | null;
  outMatThick: number | null;
  seriesData: number[];
}
const coilSegments = ref<CoilSegment[]>([]);
// 连退卷段信息
const continuousRefundSegments = ref<CoilSegment[]>([]);
// 镀锌卷段信息
const galvanizingSegments = ref<CoilSegment[]>([]);

// 弹窗相关
const dialogVisible = ref(false);
const dialogCoilNo = ref<string>('');
const dialogXData = ref<number[]>([]);
const dialogYData = ref<number[]>([]);
const dialogMidline = ref<number | null>(null);
const dialogUpper = ref<number | null>(null);
const dialogLower = ref<number | null>(null);

// 初始化下一卷图表
const initNextCoilChart = () => {
  if (!nextCoilChartRef.value) return;

  const inferredLenInit = Math.max(
    nextCoilXData.value?.length || 0,
    nextCoilYData.value?.length || 0,
    currentThkData.value?.length || 0,
    (Array.isArray(nextCoilUpperline.value) ? nextCoilUpperline.value.length : 0),
    (Array.isArray(nextCoilThreshold.value) ? nextCoilThreshold.value.length : 0),
    (Array.isArray(nextCoilMidline.value) ? nextCoilMidline.value.length : 0),
    0
  );
  const xDataInit = nextCoilXData.value?.length ? nextCoilXData.value : Array.from({ length: inferredLenInit }, (_, i) => i + 1);
  const baseMidValOrArr = nextCoilMidline.value as any;
  const isMidArray = Array.isArray(baseMidValOrArr) && baseMidValOrArr.length > 0;
  const baseMidNum: number | null = !isMidArray && typeof baseMidValOrArr === 'number' ? baseMidValOrArr : null;
  const baseMidArr: Array<number | null> = isMidArray ? baseMidValOrArr : [];

  // 原始值
  const mainInitRaw = nextCoilYData.value?.length ? nextCoilYData.value : new Array(inferredLenInit).fill(null);
  const rtAvgInitRaw = currentThkData.value?.length ? currentThkData.value : new Array(inferredLenInit).fill(null);
  const upperInitRaw = nextCoilUpperline.value?.length ? nextCoilUpperline.value : new Array(inferredLenInit).fill(null);
  const lowerInitRaw = nextCoilThreshold.value?.length ? nextCoilThreshold.value : new Array(inferredLenInit).fill(null);

  const toDeviation = (arr: any[]): any[] => {
    if (baseMidNum != null) {
      return arr.map((v: any) => (v == null ? null : Number(v) - baseMidNum));
    }
    if (isMidArray) {
      return Array.from({ length: inferredLenInit }, (_, i) => {
        const v = arr[i];
        const m = baseMidArr[i] as any;
        if (v == null || m == null || Number.isNaN(Number(m))) return null;
        return Number(v) - Number(m);
      });
    }
    return arr;
  };

  // 偏差值（让中线作为 y=0）
  const mainInit = (baseMidNum != null || isMidArray) ? toDeviation(mainInitRaw) : mainInitRaw;
  const rtAvgInit = (baseMidNum != null || isMidArray) ? toDeviation(rtAvgInitRaw) : rtAvgInitRaw;
  const upperInit = (baseMidNum != null || isMidArray) ? toDeviation(upperInitRaw) : upperInitRaw;
  const lowerInit = (baseMidNum != null || isMidArray) ? toDeviation(lowerInitRaw) : lowerInitRaw;
  const midInit = new Array(inferredLenInit).fill((baseMidNum != null || isMidArray) ? 0 : null);

  const option = {
    backgroundColor: 'transparent',
    grid: {
      left: '8%',
      right: '8%',
      bottom: '15%',
      top: '10%',
      containLabel: false,
    },
    xAxis: {
      type: 'category',
      data: xDataInit,
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
      axisLabel: {
        color: '#fff',
        fontSize: 12,
        formatter: (value: number) => {
          if (value === 5) return '5(m)';
          return value.toString();
        },
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)',
          type: 'dashed',
        },
      },
    },
    yAxis: {
      type: 'value',
      interval: 5,
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
      axisLabel: {
        color: '#fff',
        fontSize: 12,
        formatter: (value: number) => value.toString(),
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)',
          type: 'dashed',
        },
      },
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#fff',
      borderWidth: 1,
      textStyle: {
        color: '#fff',
      },
      formatter: (params: any[]) => {
        if (!Array.isArray(params) || params.length === 0) return '';
        const name = params[0]?.name ?? '';
        const idx = params[0]?.dataIndex ?? 0;
        const baseValOrArr: any = nextCoilMidline.value as any;
        const isArrayBase = Array.isArray(baseValOrArr) && baseValOrArr.length > 0;
        const baseAtIdx: number | null = isArrayBase
          ? (Number.isNaN(Number(baseValOrArr[idx])) ? null : Number(baseValOrArr[idx]))
          : (typeof baseValOrArr === 'number' ? baseValOrArr : null);
        const rows = params
          .filter(p => p != null && p.value != null)
          .map(p => {
            const val = Number(p.value);
            const display = (baseAtIdx != null && !Number.isNaN(val)) ? (val + baseAtIdx) : p.value;
            return `${p.marker || ''}${p.seriesName}: ${display}mm`;
          });
        return `${name}m<br/>${rows.join('<br/>')}`;
      },
    },
    series: [
      {
        name: '厚度值',
        type: 'line',
        color: '#00ff00',
        data: mainInit,
        smooth: false,
        lineStyle: {
          color: '#00ff00',
          width: 2,
        },
        itemStyle: {
          color: '#00ff00',
        },
        symbol: 'circle',
        symbolSize: 4,
        areaStyle: {
          opacity: 0,
        },
      },
      {
        name: '实时厚度平均值',
        type: 'line',
        color: '#1E90FF',
        data: rtAvgInit,
        smooth: true,
        lineStyle: {
          color: '#1E90FF',
          width: 2,
        },
        itemStyle: {
          color: '#1E90FF',
        },
        symbol: 'circle',
        showAllSymbol: true,
        symbolSize: 6,
        areaStyle: {
          opacity: 0,
        },
      },
      {
        name: '中线',
        type: 'line',
        color: '#FFD700',
        data: midInit,
        lineStyle: {
          color: '#FFD700',
          width: 2,
          type: 'dashed',
        },
        symbol: 'none',
        silent: true,
      },
      {
        name: '上限',
        type: 'line',
        color: '#FFA500',
        data: upperInit,
        lineStyle: {
          color: '#FFA500',
          width: 2,
          type: 'solid',
        },
        symbol: 'none',
        silent: true,
      },
      {
        name: '下限',
        type: 'line',
        color: '#ff0000',
        data: lowerInit,
        lineStyle: {
          color: '#ff0000',
          width: 2,
          type: 'solid',
        },
        symbol: 'none',
        silent: true,
      },
    ],
  };

  nextCoilChartInstance = echarts.init(nextCoilChartRef.value);
  nextCoilChartInstance.setOption(option);

  // 绑定点击事件：点击蓝色点弹出对应卷曲线
  nextCoilChartInstance.off('click');
  nextCoilChartInstance.on('click', (params: any) => {
    console.log("111111111111111")
    if (!params || typeof params.dataIndex !== 'number') return;
    const idx: number = params.dataIndex;
    const seg = coilSegments.value.find(s => idx >= s.startIndex && idx <= s.endIndex);
    if (seg) {
      const len = seg.seriesData.length;
      dialogCoilNo.value = seg.coilNo || (String(seg.extid) || '-');
      dialogXData.value = Array.from({ length: len }, (_, i) => i + 1);
      dialogYData.value = seg.seriesData.slice();
      dialogMidline.value = seg.outMatThick ?? null;
      dialogUpper.value = seg.exThkMax ?? null;
      dialogLower.value = seg.exThkMin ?? null;
    } else {
      // 无分段信息时，优先用最近分段的上下限/中线；否则退化到按索引取数组
      const totalLen = currentThkData.value.length || 0;
      dialogCoilNo.value = '-';
      dialogXData.value = Array.from({ length: totalLen }, (_, i) => i + 1);
      dialogYData.value = currentThkData.value.slice();
      const segNear = coilSegments.value
        .filter(s => typeof s.startIndex === 'number')
        .sort((a, b) => Math.abs(idx - a.startIndex) - Math.abs(idx - b.startIndex))[0];
      if (segNear) {
        dialogMidline.value = segNear.outMatThick ?? null;
        dialogUpper.value = segNear.exThkMax ?? null;
        dialogLower.value = segNear.exThkMin ?? null;
      } else {
        const midAny: any = nextCoilMidline.value as any;
        const upAny: any = nextCoilUpperline.value as any;
        const lowAny: any = nextCoilThreshold.value as any;
        dialogMidline.value =
          (Array.isArray(midAny) ? (Number.isFinite(Number(midAny[idx])) ? Number(midAny[idx]) : null)
            : (typeof midAny === 'number' ? midAny : null));
        dialogUpper.value =
          (Array.isArray(upAny) ? (Number.isFinite(Number(upAny[idx])) ? Number(upAny[idx]) : null)
            : (typeof upAny === 'number' ? upAny : null));
        dialogLower.value =
          (Array.isArray(lowAny) ? (Number.isFinite(Number(lowAny[idx])) ? Number(lowAny[idx]) : null)
            : (typeof lowAny === 'number' ? lowAny : null));
      }
    }
    if (dialogVisible.value) {
      // 若弹窗已打开，则直接刷新图表
      initOrUpdateDialogChart();
    } else {
      dialogVisible.value = true;
      setTimeout(() => {
        initOrUpdateDialogChart();
      }, 0);
    }
  });
  // 低级别点击事件日志（用于排查是否被覆盖）
  nextCoilChartInstance.getZr().off('click');
  nextCoilChartInstance.getZr().on('click', (zrEvent: any) => {
    void (async () => {
      console.log('zr-click');
      try {
        if (!zrEvent || typeof zrEvent.offsetX !== 'number' || typeof zrEvent.offsetY !== 'number') return;
        const point = [zrEvent.offsetX, zrEvent.offsetY];
        const coord = nextCoilChartInstance?.convertFromPixel({ gridIndex: 0 }, point) as any;
        if (!coord || !Array.isArray(coord)) return;
        // x 轴是 1..N 或类目坐标，计算最近索引
        const xCoord = Number(coord[0]);
        if (Number.isNaN(xCoord)) return;
        let idx = Math.round(xCoord - 1);
        const totalLen = currentThkData.value.length || 0;
        if (totalLen <= 0) return;
        if (idx < 0) idx = 0;
        if (idx > totalLen - 1) idx = totalLen - 1;

        const seg = coilSegments.value.find(s => idx >= s.startIndex && idx <= s.endIndex);
        if (seg) {
          dialogCoilNo.value = seg.coilNo || (String(seg.extid) || '-');
          const graphParam = {
            line: 'TCM2280',
            extid: [seg.extid],
            curve: ["tcm_exs5_thk_act"],
          };
          console.log('获取图表数据参数:', graphParam);
          const response = await historyApi.getgraphData(graphParam);
          const curve = response?.data?.data?.curve?.[0];
          if (curve) {
            dialogYData.value = (curve as any).tcm_exs5_thk_act;
            const values = Array.isArray(dialogYData.value) ? dialogYData.value : [dialogYData.value];
            const numericValues = values
              .map((v: any) => Number(v))
              .filter((v: number) => !Number.isNaN(v));
            dialogXData.value = Array.from({ length: numericValues.length }, (_, i) => i + 1);
            dialogMidline.value = seg.outMatThick ?? null;
            dialogUpper.value = seg.exThkMax ?? null;
            dialogLower.value = seg.exThkMin ?? null;
          }
        } else {
          console.log("22222222222")
          dialogCoilNo.value = '-';
          dialogXData.value = Array.from({ length: totalLen }, (_, i) => i + 1);
          dialogYData.value = currentThkData.value.slice();
          const segNear = coilSegments.value
            .filter(s => typeof s.startIndex === 'number')
            .sort((a, b) => Math.abs(idx - a.startIndex) - Math.abs(idx - b.startIndex))[0];
          if (segNear) {
            dialogMidline.value = segNear.outMatThick ?? null;
            dialogUpper.value = segNear.exThkMax ?? null;
            dialogLower.value = segNear.exThkMin ?? null;
          } else {
            const midAny: any = nextCoilMidline.value as any;
            const upAny: any = nextCoilUpperline.value as any;
            const lowAny: any = nextCoilThreshold.value as any;
            dialogMidline.value =
              (Array.isArray(midAny) ? (Number.isFinite(Number(midAny[idx])) ? Number(midAny[idx]) : null)
                : (typeof midAny === 'number' ? midAny : null));
            dialogUpper.value =
              (Array.isArray(upAny) ? (Number.isFinite(Number(upAny[idx])) ? Number(upAny[idx]) : null)
                : (typeof upAny === 'number' ? upAny : null));
            dialogLower.value =
              (Array.isArray(lowAny) ? (Number.isFinite(Number(lowAny[idx])) ? Number(lowAny[idx]) : null)
                : (typeof lowAny === 'number' ? lowAny : null));
          }
        }
        if (dialogVisible.value) {
          initOrUpdateDialogChart();
        } else {
          dialogVisible.value = true;
          setTimeout(() => initOrUpdateDialogChart(), 0);
        }
      } catch (e) {
        console.warn('zr-click handler error:', e);
      }
    })();
  });
};

// 初始化当前卷图表
const initCurrentCoilChart = () => {
  if (!currentCoilChartRef.value) return;

  const option = {
    backgroundColor: 'transparent',
    grid: {
      left: '8%',
      right: '8%',
      bottom: '15%',
      top: '10%',
      containLabel: false,
    },
    xAxis: {
      type: 'category',
      data: currentCoilXData.value,
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
      axisLabel: {
        color: '#fff',
        fontSize: 12,
        formatter: (value: number) => {
          if (value === 4) return '4(m)';
          return value.toString();
        },
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)',
          type: 'dashed',
        },
      },
    },
    yAxis: {
      type: 'value',
      interval: 10,
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
      axisLabel: {
        color: '#fff',
        fontSize: 12,
        formatter: (value: number) => value.toString(),
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#fff',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)',
          type: 'dashed',
        },
      },
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#fff',
      borderWidth: 1,
      textStyle: {
        color: '#fff',
      },
      formatter: (params: any) => {
        const param = params[0];
        return `${param.name}m<br/>${param.seriesName}: ${param.value}mm`;
      },
    },
    series: [
      {
        name: '厚度值',
        type: 'line',
        data: currentCoilYData.value,
        smooth: false,
        lineStyle: {
          color: '#00ff00',
          width: 2,
        },
        itemStyle: {
          color: '#00ff00',
        },
        symbol: 'circle',
        symbolSize: 4,
        areaStyle: {
          opacity: 0,
        },
      },
      {
        name: '下限',
        type: 'line',
        data: new Array(currentCoilXData.value.length).fill(currentCoilThreshold.value),
        lineStyle: {
          color: '#ff0000',
          width: 2,
          type: 'solid',
        },
        symbol: 'none',
        silent: true,
      },
    ],
  };

  currentCoilChartInstance = echarts.init(currentCoilChartRef.value);
  currentCoilChartInstance.setOption(option);
};

// 初始化连退图表
const initContinuousRefundChart = () => {
  if (!continuousRefundChartRef.value) return;

  const inferredLenInit = Math.max(
    continuousRefundXData.value?.length || 0,
    continuousRefundYData.value?.length || 0,
    (Array.isArray(continuousRefundUpperline.value) ? continuousRefundUpperline.value.length : 0),
    (Array.isArray(continuousRefundThreshold.value) ? continuousRefundThreshold.value.length : 0),
    (Array.isArray(continuousRefundMidline.value) ? continuousRefundMidline.value.length : 0),
    0
  );
  const xDataInit = continuousRefundXData.value?.length ? continuousRefundXData.value : Array.from({ length: inferredLenInit }, (_, i) => i + 1);
  const baseMidValOrArr = continuousRefundMidline.value as any;
  const isMidArray = Array.isArray(baseMidValOrArr) && baseMidValOrArr.length > 0;
  const baseMidNum: number | null = !isMidArray && typeof baseMidValOrArr === 'number' ? baseMidValOrArr : null;
  const baseMidArr: Array<number | null> = isMidArray ? baseMidValOrArr : [];

  // 原始值
  const mainInitRaw = continuousRefundYData.value?.length ? continuousRefundYData.value : new Array(inferredLenInit).fill(null);
  const upperInitRaw = continuousRefundUpperline.value?.length ? continuousRefundUpperline.value : new Array(inferredLenInit).fill(null);
  const lowerInitRaw = continuousRefundThreshold.value?.length ? continuousRefundThreshold.value : new Array(inferredLenInit).fill(null);

  const toDeviation = (arr: any[]): any[] => {
    if (baseMidNum != null) {
      return arr.map((v: any) => (v == null ? null : Number(v) - baseMidNum));
    }
    if (isMidArray) {
      return Array.from({ length: inferredLenInit }, (_, i) => {
        const v = arr[i];
        const m = baseMidArr[i] as any;
        if (v == null || m == null || Number.isNaN(Number(m))) return null;
        return Number(v) - Number(m);
      });
    }
    return arr;
  };

  // 偏差值（让中线作为 y=0）
  const mainInit = (baseMidNum != null || isMidArray) ? toDeviation(mainInitRaw) : mainInitRaw;
  const upperInit = (baseMidNum != null || isMidArray) ? toDeviation(upperInitRaw) : upperInitRaw;
  const lowerInit = (baseMidNum != null || isMidArray) ? toDeviation(lowerInitRaw) : lowerInitRaw;
  const midInit = new Array(inferredLenInit).fill((baseMidNum != null || isMidArray) ? 0 : null);

  const option = {
    backgroundColor: 'transparent',
    grid: { left: '8%', right: '8%', bottom: '15%', top: '10%', containLabel: false },
    xAxis: { type: 'category', data: xDataInit, boundaryGap: false, axisLine: { lineStyle: { color: '#fff' } }, axisLabel: { color: '#fff', fontSize: 12 }, axisTick: { show: true, lineStyle: { color: '#fff' } }, splitLine: { show: true, lineStyle: { color: 'rgba(255,255,255,0.1)', type: 'dashed' } } },
    yAxis: { type: 'value', interval: 5, axisLine: { lineStyle: { color: '#fff' } }, axisLabel: { color: '#fff', fontSize: 12, formatter: (value: number) => value.toString() }, axisTick: { show: true, lineStyle: { color: '#fff' } }, splitLine: { show: true, lineStyle: { color: 'rgba(255,255,255,0.1)', type: 'dashed' } } },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#fff',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      formatter: (params: any[]) => {
        if (!Array.isArray(params) || params.length === 0) return '';
        const name = params[0]?.name ?? '';
        const idx = params[0]?.dataIndex ?? 0;
        const baseValOrArr: any = continuousRefundMidline.value as any;
        const isArrayBase = Array.isArray(baseValOrArr) && baseValOrArr.length > 0;
        const baseAtIdx: number | null = isArrayBase
          ? (Number.isNaN(Number(baseValOrArr[idx])) ? null : Number(baseValOrArr[idx]))
          : (typeof baseValOrArr === 'number' ? baseValOrArr : null);
        const rows = params
          .filter(p => p != null && p.value != null)
          .map(p => {
            const val = Number(p.value);
            const display = (baseAtIdx != null && !Number.isNaN(val)) ? (val + baseAtIdx) : p.value;
            return `${p.marker || ''}${p.seriesName}: ${display}mm`;
          });
        return `${name}<br/>${rows.join('<br/>')}`;
      },
    },
    series: [
      { name: '厚度值', type: 'line', color: '#00ff00', data: mainInit, symbol: 'circle', symbolSize: 4, lineStyle: { width: 2 }, areaStyle: { opacity: 0 } },
      { name: '中线', type: 'line', color: '#FFD700', data: midInit, symbol: 'none', lineStyle: { width: 2, type: 'dashed' }, silent: true },
      { name: '上限', type: 'line', color: '#FFA500', data: upperInit, symbol: 'none', lineStyle: { width: 2 }, silent: true },
      { name: '下限', type: 'line', color: '#ff0000', data: lowerInit, symbol: 'none', lineStyle: { width: 2 }, silent: true },
    ],
  };
  continuousRefundChartInstance = echarts.init(continuousRefundChartRef.value);
  continuousRefundChartInstance.setOption(option);

  // 绑定点击事件：点击厚度值弹出对应卷曲线
  continuousRefundChartInstance.off('click');
  continuousRefundChartInstance.on('click', (params: any) => {
    if (!params || typeof params.dataIndex !== 'number') return;
    const idx: number = params.dataIndex;
    const seg = continuousRefundSegments.value.find(s => idx >= s.startIndex && idx <= s.endIndex);
    if (seg) {
      dialogCoilNo.value = seg.coilNo || (String(seg.extid) || '-');
      const len = seg.seriesData.length;
      dialogXData.value = Array.from({ length: len }, (_, i) => i + 1);
      dialogYData.value = seg.seriesData.slice();
      dialogMidline.value = seg.outMatThick ?? null;
      dialogUpper.value = seg.exThkMax ?? null;
      dialogLower.value = seg.exThkMin ?? null;
    } else {
      // 无分段信息时，优先用最近分段的上下限/中线；否则退化到按索引取数组
      const totalLen = continuousRefundYData.value.length || 0;
      dialogCoilNo.value = '-';
      dialogXData.value = Array.from({ length: totalLen }, (_, i) => i + 1);
      dialogYData.value = continuousRefundYData.value.slice();
      const segNear = continuousRefundSegments.value
        .filter(s => typeof s.startIndex === 'number')
        .sort((a, b) => Math.abs(idx - a.startIndex) - Math.abs(idx - b.startIndex))[0];
      if (segNear) {
        dialogMidline.value = segNear.outMatThick ?? null;
        dialogUpper.value = segNear.exThkMax ?? null;
        dialogLower.value = segNear.exThkMin ?? null;
      } else {
        const midAny: any = continuousRefundMidline.value as any;
        const upAny: any = continuousRefundUpperline.value as any;
        const lowAny: any = continuousRefundThreshold.value as any;
        dialogMidline.value =
          (Array.isArray(midAny) ? (Number.isFinite(Number(midAny[idx])) ? Number(midAny[idx]) : null)
            : (typeof midAny === 'number' ? midAny : null));
        dialogUpper.value =
          (Array.isArray(upAny) ? (Number.isFinite(Number(upAny[idx])) ? Number(upAny[idx]) : null)
            : (typeof upAny === 'number' ? upAny : null));
        dialogLower.value =
          (Array.isArray(lowAny) ? (Number.isFinite(Number(lowAny[idx])) ? Number(lowAny[idx]) : null)
            : (typeof lowAny === 'number' ? lowAny : null));
      }
    }
    if (dialogVisible.value) {
      // 若弹窗已打开，则直接刷新图表
      initOrUpdateDialogChart();
    } else {
      dialogVisible.value = true;
      setTimeout(() => {
        initOrUpdateDialogChart();
      }, 0);
    }
  });
  // 低级别点击事件：通过坐标转换获取点击位置，然后调用API获取详细曲线数据
  continuousRefundChartInstance.getZr().off('click');
  continuousRefundChartInstance.getZr().on('click', (zrEvent: any) => {
    void (async () => {
    try {
      if (!zrEvent || typeof zrEvent.offsetX !== 'number' || typeof zrEvent.offsetY !== 'number') return;
      const point = [zrEvent.offsetX, zrEvent.offsetY];
      const coord = continuousRefundChartInstance?.convertFromPixel({ gridIndex: 0 }, point) as any;
      if (!coord || !Array.isArray(coord)) return;
      // x 轴是 1..N 或类目坐标，计算最近索引
      const xCoord = Number(coord[0]);
      if (Number.isNaN(xCoord)) return;
      let idx = Math.round(xCoord - 1);
      const totalLen = continuousRefundYData.value.length || 0;
      if (totalLen <= 0) return;
      if (idx < 0) idx = 0;
      if (idx > totalLen - 1) idx = totalLen - 1;

      const seg = continuousRefundSegments.value.find(s => idx >= s.startIndex && idx <= s.endIndex);
      if (seg && seg.extid) {
        dialogCoilNo.value = seg.coilNo || (String(seg.extid) || '-');
        const graphParam = {
          line: 'CAL1630',
          extid: [seg.extid],
          curve: ["cal_ex_thk_guage"],
        };
        console.log('获取连退图表详细数据参数:', graphParam);
        const response = await historyApi.getgraphData(graphParam);
        const curve = response?.data?.data?.curve?.[0];
        if (curve) {
          dialogYData.value = (curve as any).cal_ex_thk_guage;
          const values = Array.isArray(dialogYData.value) ? dialogYData.value : [dialogYData.value];
          const numericValues = values
            .map((v: any) => Number(v))
            .filter((v: number) => !Number.isNaN(v));
          dialogXData.value = Array.from({ length: numericValues.length }, (_, i) => i + 1);
          dialogMidline.value = seg.outMatThick ?? null;
          dialogUpper.value = seg.exThkMax ?? null;
          dialogLower.value = seg.exThkMin ?? null;
        } else {
          // 如果没有获取到详细曲线，使用平均值数据
          dialogYData.value = seg.seriesData.slice();
          dialogXData.value = Array.from({ length: seg.seriesData.length }, (_, i) => i + 1);
          dialogMidline.value = seg.outMatThick ?? null;
          dialogUpper.value = seg.exThkMax ?? null;
          dialogLower.value = seg.exThkMin ?? null;
        }
      } else {
        dialogCoilNo.value = '-';
        dialogXData.value = Array.from({ length: totalLen }, (_, i) => i + 1);
        dialogYData.value = continuousRefundYData.value.slice();
        const segNear = continuousRefundSegments.value
          .filter(s => typeof s.startIndex === 'number')
          .sort((a, b) => Math.abs(idx - a.startIndex) - Math.abs(idx - b.startIndex))[0];
        if (segNear) {
          dialogMidline.value = segNear.outMatThick ?? null;
          dialogUpper.value = segNear.exThkMax ?? null;
          dialogLower.value = segNear.exThkMin ?? null;
        } else {
          const midAny: any = continuousRefundMidline.value as any;
          const upAny: any = continuousRefundUpperline.value as any;
          const lowAny: any = continuousRefundThreshold.value as any;
          dialogMidline.value =
            (Array.isArray(midAny) ? (Number.isFinite(Number(midAny[idx])) ? Number(midAny[idx]) : null)
              : (typeof midAny === 'number' ? midAny : null));
          dialogUpper.value =
            (Array.isArray(upAny) ? (Number.isFinite(Number(upAny[idx])) ? Number(upAny[idx]) : null)
              : (typeof upAny === 'number' ? upAny : null));
          dialogLower.value =
            (Array.isArray(lowAny) ? (Number.isFinite(Number(lowAny[idx])) ? Number(lowAny[idx]) : null)
              : (typeof lowAny === 'number' ? lowAny : null));
        }
      }
      if (dialogVisible.value) {
        initOrUpdateDialogChart();
      } else {
        dialogVisible.value = true;
        setTimeout(() => initOrUpdateDialogChart(), 0);
      }
    } catch (e) {
      console.warn('连退图表点击事件处理错误:', e);
    }
    })();
  });
};

// 初始化镀锌图表
const initGalvanizingChart = () => {
  if (!galvanizingChartRef.value) return;

  // 如果实例已存在，先销毁
  if (galvanizingChartInstance) {
    galvanizingChartInstance.dispose();
    galvanizingChartInstance = null;
  }

  const inferredLenInit = Math.max(
    galvanizingXData.value?.length || 0,
    galvanizingYData.value?.length || 0,
    (Array.isArray(galvanizingUpperline.value) ? galvanizingUpperline.value.length : 0),
    (Array.isArray(galvanizingThreshold.value) ? galvanizingThreshold.value.length : 0),
    (Array.isArray(galvanizingMidline.value) ? galvanizingMidline.value.length : 0),
    0
  );
  
  console.log('镀锌图表初始化 - 数据长度:', {
    xData: galvanizingXData.value?.length || 0,
    yData: galvanizingYData.value?.length || 0,
    upperline: Array.isArray(galvanizingUpperline.value) ? galvanizingUpperline.value.length : 0,
    threshold: Array.isArray(galvanizingThreshold.value) ? galvanizingThreshold.value.length : 0,
    midline: Array.isArray(galvanizingMidline.value) ? galvanizingMidline.value.length : 0,
    inferredLen: inferredLenInit
  });
  
  // 如果没有数据，不初始化图表
  if (inferredLenInit === 0) {
    console.warn('镀锌图表初始化失败：没有数据');
    return;
  }
  
  const xDataInit = galvanizingXData.value?.length ? galvanizingXData.value : Array.from({ length: inferredLenInit }, (_, i) => i + 1);
  const baseMidValOrArr = galvanizingMidline.value as any;
  const isMidArray = Array.isArray(baseMidValOrArr) && baseMidValOrArr.length > 0;
  const baseMidNum: number | null = !isMidArray && typeof baseMidValOrArr === 'number' ? baseMidValOrArr : null;
  const baseMidArr: Array<number | null> = isMidArray ? baseMidValOrArr : [];

  // 原始值
  const mainInitRaw = galvanizingYData.value?.length ? galvanizingYData.value : new Array(inferredLenInit).fill(null);
  const upperInitRaw = galvanizingUpperline.value?.length ? galvanizingUpperline.value : new Array(inferredLenInit).fill(null);
  const lowerInitRaw = galvanizingThreshold.value?.length ? galvanizingThreshold.value : new Array(inferredLenInit).fill(null);

  const toDeviation = (arr: any[]): any[] => {
    if (baseMidNum != null) {
      return arr.map((v: any) => (v == null ? null : Number(v) - baseMidNum));
    }
    if (isMidArray) {
      return Array.from({ length: inferredLenInit }, (_, i) => {
        const v = arr[i];
        const m = baseMidArr[i] as any;
        if (v == null || m == null || Number.isNaN(Number(m))) return null;
        return Number(v) - Number(m);
      });
    }
    return arr;
  };

  // 偏差值（让中线作为 y=0）
  const mainInit = (baseMidNum != null || isMidArray) ? toDeviation(mainInitRaw) : mainInitRaw;
  const upperInit = (baseMidNum != null || isMidArray) ? toDeviation(upperInitRaw) : upperInitRaw;
  const lowerInit = (baseMidNum != null || isMidArray) ? toDeviation(lowerInitRaw) : lowerInitRaw;
  const midInit = new Array(inferredLenInit).fill((baseMidNum != null || isMidArray) ? 0 : null);

  const option = {
    backgroundColor: 'transparent',
    grid: { left: '8%', right: '8%', bottom: '15%', top: '10%', containLabel: false },
    xAxis: { type: 'category', data: xDataInit, boundaryGap: false, axisLine: { lineStyle: { color: '#fff' } }, axisLabel: { color: '#fff', fontSize: 12 }, axisTick: { show: true, lineStyle: { color: '#fff' } }, splitLine: { show: true, lineStyle: { color: 'rgba(255,255,255,0.1)', type: 'dashed' } } },
    yAxis: { type: 'value', interval: 5, axisLine: { lineStyle: { color: '#fff' } }, axisLabel: { color: '#fff', fontSize: 12, formatter: (value: number) => value.toString() }, axisTick: { show: true, lineStyle: { color: '#fff' } }, splitLine: { show: true, lineStyle: { color: 'rgba(255,255,255,0.1)', type: 'dashed' } } },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#fff',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      formatter: (params: any[]) => {
        if (!Array.isArray(params) || params.length === 0) return '';
        const name = params[0]?.name ?? '';
        const idx = params[0]?.dataIndex ?? 0;
        const baseValOrArr: any = galvanizingMidline.value as any;
        const isArrayBase = Array.isArray(baseValOrArr) && baseValOrArr.length > 0;
        const baseAtIdx: number | null = isArrayBase
          ? (Number.isNaN(Number(baseValOrArr[idx])) ? null : Number(baseValOrArr[idx]))
          : (typeof baseValOrArr === 'number' ? baseValOrArr : null);
        const rows = params
          .filter(p => p != null && p.value != null)
          .map(p => {
            const val = Number(p.value);
            const display = (baseAtIdx != null && !Number.isNaN(val)) ? (val + baseAtIdx) : p.value;
            return `${p.marker || ''}${p.seriesName}: ${display}mm`;
          });
        return `${name}<br/>${rows.join('<br/>')}`;
      },
    },
    series: [
      { name: '厚度值', type: 'line', color: '#00ff00', data: mainInit, symbol: 'circle', symbolSize: 4, lineStyle: { width: 2 }, areaStyle: { opacity: 0 } },
      { name: '中线', type: 'line', color: '#FFD700', data: midInit, symbol: 'none', lineStyle: { width: 2, type: 'dashed' }, silent: true },
      { name: '上限', type: 'line', color: '#FFA500', data: upperInit, symbol: 'none', lineStyle: { width: 2 }, silent: true },
      { name: '下限', type: 'line', color: '#ff0000', data: lowerInit, symbol: 'none', lineStyle: { width: 2 }, silent: true },
    ],
  };
  galvanizingChartInstance = echarts.init(galvanizingChartRef.value);
  galvanizingChartInstance.setOption(option);

  // 绑定点击事件：点击厚度值弹出对应卷曲线
  galvanizingChartInstance.off('click');
  galvanizingChartInstance.on('click', (params: any) => {
    if (!params || typeof params.dataIndex !== 'number') return;
    const idx: number = params.dataIndex;
    const seg = galvanizingSegments.value.find(s => idx >= s.startIndex && idx <= s.endIndex);
    if (seg) {
      dialogCoilNo.value = seg.coilNo || (String(seg.extid) || '-');
      const len = seg.seriesData.length;
      dialogXData.value = Array.from({ length: len }, (_, i) => i + 1);
      dialogYData.value = seg.seriesData.slice();
      dialogMidline.value = seg.outMatThick ?? null;
      dialogUpper.value = seg.exThkMax ?? null;
      dialogLower.value = seg.exThkMin ?? null;
    } else {
      // 无分段信息时，优先用最近分段的上下限/中线；否则退化到按索引取数组
      const totalLen = galvanizingYData.value.length || 0;
      dialogCoilNo.value = '-';
      dialogXData.value = Array.from({ length: totalLen }, (_, i) => i + 1);
      dialogYData.value = galvanizingYData.value.slice();
      const segNear = galvanizingSegments.value
        .filter(s => typeof s.startIndex === 'number')
        .sort((a, b) => Math.abs(idx - a.startIndex) - Math.abs(idx - b.startIndex))[0];
      if (segNear) {
        dialogMidline.value = segNear.outMatThick ?? null;
        dialogUpper.value = segNear.exThkMax ?? null;
        dialogLower.value = segNear.exThkMin ?? null;
      } else {
        const midAny: any = galvanizingMidline.value as any;
        const upAny: any = galvanizingUpperline.value as any;
        const lowAny: any = galvanizingThreshold.value as any;
        dialogMidline.value =
          (Array.isArray(midAny) ? (Number.isFinite(Number(midAny[idx])) ? Number(midAny[idx]) : null)
            : (typeof midAny === 'number' ? midAny : null));
        dialogUpper.value =
          (Array.isArray(upAny) ? (Number.isFinite(Number(upAny[idx])) ? Number(upAny[idx]) : null)
            : (typeof upAny === 'number' ? upAny : null));
        dialogLower.value =
          (Array.isArray(lowAny) ? (Number.isFinite(Number(lowAny[idx])) ? Number(lowAny[idx]) : null)
            : (typeof lowAny === 'number' ? lowAny : null));
      }
    }
    if (dialogVisible.value) {
      // 若弹窗已打开，则直接刷新图表
      initOrUpdateDialogChart();
    } else {
      dialogVisible.value = true;
      setTimeout(() => {
        initOrUpdateDialogChart();
      }, 0);
    }
  });
  // 低级别点击事件：通过坐标转换获取点击位置，然后调用API获取详细曲线数据
  galvanizingChartInstance.getZr().off('click');
  galvanizingChartInstance.getZr().on('click', (zrEvent: any) => {
    void (async () => {
    try {
      if (!zrEvent || typeof zrEvent.offsetX !== 'number' || typeof zrEvent.offsetY !== 'number') return;
      const point = [zrEvent.offsetX, zrEvent.offsetY];
      const coord = galvanizingChartInstance?.convertFromPixel({ gridIndex: 0 }, point) as any;
      if (!coord || !Array.isArray(coord)) return;
      // x 轴是 1..N 或类目坐标，计算最近索引
      const xCoord = Number(coord[0]);
      if (Number.isNaN(xCoord)) return;
      let idx = Math.round(xCoord - 1);
      const totalLen = galvanizingYData.value.length || 0;
      if (totalLen <= 0) return;
      if (idx < 0) idx = 0;
      if (idx > totalLen - 1) idx = totalLen - 1;

      const seg = galvanizingSegments.value.find(s => idx >= s.startIndex && idx <= s.endIndex);
      if (seg && seg.extid) {
        dialogCoilNo.value = seg.coilNo || (String(seg.extid) || '-');
        const graphParam = {
          line: 'CGL1870',
          extid: [seg.extid],
          curve: ["cgl_ex_gauge thk"],
        };
        console.log('获取镀锌图表详细数据参数:', graphParam);
        const response = await historyApi.getgraphData(graphParam);
        const curve = response?.data?.data?.curve?.[0];
        if (curve) {
          dialogYData.value = (curve as any)['cgl_ex_gauge thk'];
          const values = Array.isArray(dialogYData.value) ? dialogYData.value : [dialogYData.value];
          const numericValues = values
            .map((v: any) => Number(v))
            .filter((v: number) => !Number.isNaN(v));
          dialogXData.value = Array.from({ length: numericValues.length }, (_, i) => i + 1);
          dialogMidline.value = seg.outMatThick ?? null;
          dialogUpper.value = seg.exThkMax ?? null;
          dialogLower.value = seg.exThkMin ?? null;
        } else {
          // 如果没有获取到详细曲线，使用平均值数据
          dialogYData.value = seg.seriesData.slice();
          dialogXData.value = Array.from({ length: seg.seriesData.length }, (_, i) => i + 1);
          dialogMidline.value = seg.outMatThick ?? null;
          dialogUpper.value = seg.exThkMax ?? null;
          dialogLower.value = seg.exThkMin ?? null;
        }
      } else {
        dialogCoilNo.value = '-';
        dialogXData.value = Array.from({ length: totalLen }, (_, i) => i + 1);
        dialogYData.value = galvanizingYData.value.slice();
        const segNear = galvanizingSegments.value
          .filter(s => typeof s.startIndex === 'number')
          .sort((a, b) => Math.abs(idx - a.startIndex) - Math.abs(idx - b.startIndex))[0];
        if (segNear) {
          dialogMidline.value = segNear.outMatThick ?? null;
          dialogUpper.value = segNear.exThkMax ?? null;
          dialogLower.value = segNear.exThkMin ?? null;
        } else {
          const midAny: any = galvanizingMidline.value as any;
          const upAny: any = galvanizingUpperline.value as any;
          const lowAny: any = galvanizingThreshold.value as any;
          dialogMidline.value =
            (Array.isArray(midAny) ? (Number.isFinite(Number(midAny[idx])) ? Number(midAny[idx]) : null)
              : (typeof midAny === 'number' ? midAny : null));
          dialogUpper.value =
            (Array.isArray(upAny) ? (Number.isFinite(Number(upAny[idx])) ? Number(upAny[idx]) : null)
              : (typeof upAny === 'number' ? upAny : null));
          dialogLower.value =
            (Array.isArray(lowAny) ? (Number.isFinite(Number(lowAny[idx])) ? Number(lowAny[idx]) : null)
              : (typeof lowAny === 'number' ? lowAny : null));
        }
      }
      if (dialogVisible.value) {
        initOrUpdateDialogChart();
      } else {
        dialogVisible.value = true;
        setTimeout(() => initOrUpdateDialogChart(), 0);
      }
    } catch (e) {
      console.warn('镀锌图表点击事件处理错误:', e);
    }
    })();
  });
};
// 初始化或更新弹窗图表
const initOrUpdateDialogChart = () => {
  if (!dialogChartRef.value) return;
  const len = dialogXData.value.length || 0;
  const midArr = dialogMidline.value != null ? new Array(len).fill(dialogMidline.value) : new Array(len).fill(null);
  const upperArr = dialogUpper.value != null ? new Array(len).fill(dialogUpper.value) : new Array(len).fill(null);
  const lowerArr = dialogLower.value != null ? new Array(len).fill(dialogLower.value) : new Array(len).fill(null);
  // 纵轴范围：最小值为小于下限的10%，最大值为大于上限的10%；若无上下限，则自适应
  let yMin: number | undefined;
  let yMax: number | undefined;
  const lowerNum = typeof dialogLower.value === 'number' ? Number(dialogLower.value) : NaN;
  const upperNum = typeof dialogUpper.value === 'number' ? Number(dialogUpper.value) : NaN;
  if (!Number.isNaN(lowerNum) && !Number.isNaN(upperNum)) {
    const lowerPad = Math.abs(lowerNum) * 0.1;
    const upperPad = Math.abs(upperNum) * 0.1;
    yMin = Number((lowerNum - lowerPad).toFixed(2));
    yMax = Number((upperNum + upperPad).toFixed(2));
    // 确保包含数据与中线
    const nums = (dialogYData.value || []).map(v => Number(v)).filter(v => Number.isFinite(v));
    if (typeof dialogMidline.value === 'number') nums.push(Number(dialogMidline.value));
    if (nums.length) {
      const dataMin = Math.min(...nums);
      const dataMax = Math.max(...nums);
      if (dataMin < (yMin as number)) yMin = Number(dataMin.toFixed(2));
      if (dataMax > (yMax as number)) yMax = Number(dataMax.toFixed(2));
    }
  } else if (!Number.isNaN(lowerNum)) {
    const lowerPad = Math.abs(lowerNum) * 0.1;
    yMin = Number((lowerNum - lowerPad).toFixed(2));
  } else if (!Number.isNaN(upperNum)) {
    const upperPad = Math.abs(upperNum) * 0.1;
    yMax = Number((upperNum + upperPad).toFixed(2));
  }
  const option = {
    backgroundColor: 'transparent',
    grid: { left: '8%', right: '8%', bottom: '15%', top: '10%', containLabel: false },
    xAxis: {
      type: 'category',
      data: dialogXData.value,
      boundaryGap: false,
      name: 'X',
      nameLocation: 'end',
      nameTextStyle: { color: '#333', fontSize: 12, padding: [0, 0, 0, 4] },
      axisLine: { lineStyle: { color: '#333' } },
      axisLabel: { color: '#333', fontSize: 12 },
      axisTick: { show: true, lineStyle: { color: '#333' } },
      splitLine: { show: true, lineStyle: { color: 'rgba(0, 0, 0, 0.08)', type: 'dashed' } },
    },
    yAxis: {
      type: 'value',
      min: yMin,
      max: yMax,
      name: 'Y',
      nameLocation: 'end',
      nameTextStyle: { color: '#333', fontSize: 12, padding: [0, 4, 0, 0] },
      axisLine: { lineStyle: { color: '#333' } },
      axisLabel: {
        color: '#333',
        fontSize: 12,
        formatter: (value: number) => {
          const n = Number(value);
          return Number.isFinite(n) ? n.toFixed(2) : '';
        }
      },
      axisTick: { show: true, lineStyle: { color: '#333' } },
      splitLine: { show: true, lineStyle: { color: 'rgba(0, 0, 0, 0.08)', type: 'dashed' } },
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#fff',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      formatter: (params: any[]) => {
        if (!Array.isArray(params) || params.length === 0) return '';
        const name = params[0]?.name ?? '';
        const rows = params
          .filter(p => p != null && p.value != null)
          .map(p => {
            const n = Number(p.value);
            const v = Number.isFinite(n) ? n.toFixed(2) : p.value;
            return `${p.marker || ''}${p.seriesName}: ${v}mm`;
          });
        return `${name}<br/>${rows.join('<br/>')}`;
      },
    },
    series: [
      { name: '厚度值', type: 'line', data: dialogYData.value, smooth: false, lineStyle: { color: '#1E90FF', width: 2 }, itemStyle: { color: '#1E90FF' }, symbol: 'circle', symbolSize: 3, areaStyle: { opacity: 0 } },
      { name: '中线', type: 'line', data: midArr, smooth: false, lineStyle: { color: '#FFD700', width: 2, type: 'dashed' }, symbol: 'none', silent: true },
      { name: '上限', type: 'line', data: upperArr, smooth: false, lineStyle: { color: '#FFA500', width: 2 }, symbol: 'none', silent: true },
      { name: '下限', type: 'line', data: lowerArr, smooth: false, lineStyle: { color: '#ff0000', width: 2 }, symbol: 'none', silent: true },
    ],
  };
  if (!dialogChartInstance) {
    dialogChartInstance = echarts.init(dialogChartRef.value);
  }
  dialogChartInstance.setOption(option);
};

// 对话框生命周期：打开时初始化图表，关闭时释放实例
const onDialogOpen = () => {
  setTimeout(() => {
    initOrUpdateDialogChart();
  }, 0);
};
const onDialogClosed = () => {
  if (dialogChartInstance) {
    dialogChartInstance.dispose();
    dialogChartInstance = null;
  }
};

// 语音报警开关变化
const handleVoiceAlarmChange = (value: boolean) => {
  console.log('语音报警:', value ? '开启' : '关闭');
  // TODO: 实现语音报警逻辑
};

// 更新图表数据
const updateCharts = () => {
  if (nextCoilChartInstance) {
    const lenCandidates = [
      nextCoilXData.value?.length || 0,
      nextCoilYData.value?.length || 0,
      currentThkData.value?.length || 0,
      (Array.isArray(nextCoilUpperline.value) ? nextCoilUpperline.value.length : 0),
      (Array.isArray(nextCoilThreshold.value) ? nextCoilThreshold.value.length : 0),
      (Array.isArray(nextCoilMidline.value) ? nextCoilMidline.value.length : 0),
    ];
    const inferredLen = Math.max(...lenCandidates, 0);
    const xData = nextCoilXData.value?.length
      ? nextCoilXData.value
      : Array.from({ length: inferredLen }, (_, i) => i + 1);
    const midValAny: any = nextCoilMidline.value as any;
    const isArrayBaseU = Array.isArray(midValAny) && midValAny.length > 0;
    const baseNumU: number | null = (!isArrayBaseU && typeof midValAny === 'number') ? midValAny : null;
    const toDevUpdate = (arr: any[] | undefined): any[] => {
      const src = Array.isArray(arr) && arr.length ? arr : new Array(inferredLen).fill(null);
      if (baseNumU != null) {
        return src.map((v: any) => (v == null ? null : Number(v) - baseNumU));
      }
      if (isArrayBaseU) {
        return Array.from({ length: inferredLen }, (_, i) => {
          const v = src[i];
          const m = midValAny[i];
          if (v == null || m == null || Number.isNaN(Number(m))) return null;
          return Number(v) - Number(m);
        });
      }
      return src;
    };

    nextCoilChartInstance.setOption({
      xAxis: {
        data: xData,
      },
      series: [
        {
          data: toDevUpdate(nextCoilYData.value as any),
        },
        {
          data: toDevUpdate(currentThkData.value as any),
        },
        {
          data: new Array(inferredLen).fill((baseNumU != null || isArrayBaseU) ? 0 : null),
        },
        {
          data: toDevUpdate(nextCoilUpperline.value as any),
        },
        {
          data: toDevUpdate(nextCoilThreshold.value as any),
        },
      ],
    });
  }

  if (currentCoilChartInstance) {
    currentCoilChartInstance.setOption({
      xAxis: {
        data: currentCoilXData.value,
      },
      series: [
        {
          data: currentCoilYData.value,
        },
        {
          data: new Array(currentCoilXData.value.length).fill(currentCoilThreshold.value),
        },
      ],
    });
  }

  // 更新连退图表
  if (continuousRefundChartInstance) {
    const lenCandidates = [
      continuousRefundXData.value?.length || 0,
      continuousRefundYData.value?.length || 0,
      (Array.isArray(continuousRefundUpperline.value) ? continuousRefundUpperline.value.length : 0),
      (Array.isArray(continuousRefundThreshold.value) ? continuousRefundThreshold.value.length : 0),
      (Array.isArray(continuousRefundMidline.value) ? continuousRefundMidline.value.length : 0),
    ];
    const inferredLen = Math.max(...lenCandidates, 0);
    const xData = continuousRefundXData.value?.length
      ? continuousRefundXData.value
      : Array.from({ length: inferredLen }, (_, i) => i + 1);
    const midValAny: any = continuousRefundMidline.value as any;
    const isArrayBaseU = Array.isArray(midValAny) && midValAny.length > 0;
    const baseNumU: number | null = (!isArrayBaseU && typeof midValAny === 'number') ? midValAny : null;
    const toDevUpdate = (arr: any[] | undefined): any[] => {
      const src = Array.isArray(arr) && arr.length ? arr : new Array(inferredLen).fill(null);
      if (baseNumU != null) {
        return src.map((v: any) => (v == null ? null : Number(v) - baseNumU));
      }
      if (isArrayBaseU) {
        return Array.from({ length: inferredLen }, (_, i) => {
          const v = src[i];
          const m = midValAny[i];
          if (v == null || m == null || Number.isNaN(Number(m))) return null;
          return Number(v) - Number(m);
        });
      }
      return src;
    };

    continuousRefundChartInstance.setOption({
      xAxis: { data: xData },
      series: [
        { data: toDevUpdate(continuousRefundYData.value as any) },
        { data: new Array(inferredLen).fill((baseNumU != null || isArrayBaseU) ? 0 : null) },
        { data: toDevUpdate(continuousRefundUpperline.value as any) },
        { data: toDevUpdate(continuousRefundThreshold.value as any) },
      ],
    });
  }

  // 更新镀锌图表
  if (galvanizingChartInstance) {
    const lenCandidates = [
      galvanizingXData.value?.length || 0,
      galvanizingYData.value?.length || 0,
      (Array.isArray(galvanizingUpperline.value) ? galvanizingUpperline.value.length : 0),
      (Array.isArray(galvanizingThreshold.value) ? galvanizingThreshold.value.length : 0),
      (Array.isArray(galvanizingMidline.value) ? galvanizingMidline.value.length : 0),
    ];
    const inferredLen = Math.max(...lenCandidates, 0);
    const xData = galvanizingXData.value?.length
      ? galvanizingXData.value
      : Array.from({ length: inferredLen }, (_, i) => i + 1);
    const midValAny: any = galvanizingMidline.value as any;
    const isArrayBaseU = Array.isArray(midValAny) && midValAny.length > 0;
    const baseNumU: number | null = (!isArrayBaseU && typeof midValAny === 'number') ? midValAny : null;
    const toDevUpdate = (arr: any[] | undefined): any[] => {
      const src = Array.isArray(arr) && arr.length ? arr : new Array(inferredLen).fill(null);
      if (baseNumU != null) {
        return src.map((v: any) => (v == null ? null : Number(v) - baseNumU));
      }
      if (isArrayBaseU) {
        return Array.from({ length: inferredLen }, (_, i) => {
          const v = src[i];
          const m = midValAny[i];
          if (v == null || m == null || Number.isNaN(Number(m))) return null;
          return Number(v) - Number(m);
        });
      }
      return src;
    };

    galvanizingChartInstance.setOption({
      xAxis: { data: xData },
      series: [
        { data: toDevUpdate(galvanizingYData.value as any) },
        { data: new Array(inferredLen).fill((baseNumU != null || isArrayBaseU) ? 0 : null) },
        { data: toDevUpdate(galvanizingUpperline.value as any) },
        { data: toDevUpdate(galvanizingThreshold.value as any) },
      ],
    });
  }
};

// 监听数据变化
watch([nextCoilYData, currentCoilYData, nextCoilThreshold, currentCoilThreshold], () => {
  updateCharts();
}, { deep: true });

// 去重函数：根据 value 字段去重
const removeDuplicates = (options: SelectOption[]): SelectOption[] => {
  const seen = new Set<string>();
  return options.filter((option) => {
    if (seen.has(option.value)) {
      return false;
    }
    seen.add(option.value);
    return true;
  });
};

// 获取数据（模拟API调用）
const fetchData = async () => {
  try {
    const params: any = {
      "condition":{
        "steelgrade":"",
        "widthClass":"",
        "orderThick":"",
        "orderCustCode":""
      }
    };
    const res = await thicknessAndLayOutJudgeApi.findOrderThkAlertBaseInfo(params);
    console.log('接口返回数据:', res.data);
    console.log('orderThick数据:', res.data?.orderThick);
    
    // 处理接口返回的数据，填充下拉框选项
    if (res.data) {
      // 钢种下拉框
      if (res.data.data && Array.isArray(res.data.data)) {
        const steelGradeList = res.data.data
          .map((item: any) => ({
            label: item.steelgrade,
            value: item.steelgrade,
          }))
          .filter((item: SelectOption) => item.value != null && item.value !== ''); // 过滤空值
        steelGradeOptions.value = removeDuplicates(steelGradeList);
      }
      
      // 厚度下拉框 - 处理多种可能的字段名
      const thicknessData = res.data.data;
      console.log('厚度数据:', thicknessData);
      if (thicknessData) {
        if (Array.isArray(thicknessData)) {
          const thicknessList = thicknessData
            .map((item: any) => ({
              label: String(item.orderThick || ''),
              value: String(item.orderThick || ''),
            }))
            .filter((item: SelectOption) => item.value != null && item.value !== ''); // 过滤空值
          thicknessOptions.value = removeDuplicates(thicknessList);
          console.log('厚度选项已填充:', thicknessOptions.value);
        } else {
          console.warn('厚度数据不是数组格式:', thicknessData);
        }
      } else {
        console.warn('未找到厚度数据字段');
      }
      
      // 客户编码下拉框
      if (res.data.data && Array.isArray(res.data.data)) {
        const customerCodeList = res.data.data
          .map((item: any) => ({
            label: item.orderCustCname,
            value: item.orderCustCode,
          }))
          .filter((item: SelectOption) => item.value != null && item.value !== ''); // 过滤空值
        customerCodeOptions.value = removeDuplicates(customerCodeList);
      }
      
      // 宽度下拉框
      if (res.data.data && Array.isArray(res.data.data)) {
        const widthList = res.data.data
          .map((item: any) => ({
            label: String(item.widthClass || ''),
            value: String(item.widthClass || ''),
          }))
          .filter((item: SelectOption) => item.value != null && item.value !== ''); // 过滤空值
        widthOptions.value = removeDuplicates(widthList);
      }
      
      // 厚度设定值下拉框
      if (res.data.data && Array.isArray(res.data.data)) {
        const thicknessSettingList = res.data.data
          .map((item: any) => ({
            label: String(item.exthkSet || ''),
            value: String(item.exthkSet || ''),
          }))
          .filter((item: SelectOption) => item.value != null && item.value !== ''); // 过滤空值
        thicknessSettingOptions.value = removeDuplicates(thicknessSettingList);
      }
    }
    
    // nextCoilNo.value = res.data.nextCoilNo;
    // currentCoilNo.value = res.data.currentCoilNo;
    // nextCoilXData.value = res.data.nextCoilX;
    // nextCoilYData.value = res.data.nextCoilY;
    // currentCoilXData.value = res.data.currentCoilX;
    // currentCoilYData.value = res.data.currentCoilY;
    // weldDistance.value = res.data.weldDistance;
  } catch (error) {
    console.error('获取基础数据失败:', error);
  }
};

// 查询曲线数据 - 酸轧
const handleQuery = async () => {
  // 验证厚度和钢种
  if (!filterParams.value.thickness || !filterParams.value.thickness.trim()) {
    ElMessage.warning('请输入厚度');
    return;
  }
  if (!filterParams.value.steelGrade || !filterParams.value.steelGrade.trim()) {
    ElMessage.warning('请选择钢种');
    return;
  }
  
  queryLoading.value = true;
  nextCoilThreshold.value=[];
  nextCoilUpperline.value=[];
  nextCoilMidline.value=[];
  currentThkData.value=[];
  coilSegments.value = [];
  try {
    // 使用下拉选择值作为查询参数
    // const params: any = {
    //   condition: {
    //     steelgrade: filterParams.value.steelGrade || "",
    //     widthClass: filterParams.value.width || "",
    //     orderThick: filterParams.value.thickness || "",
    //     orderCustCode: filterParams.value.customerCode || "",
    //     // 如果后续恢复厚度设定值下拉框，可一并传参：
    //     // exthkSet: filterParams.value.thicknessSetting || "",
    //   }
    // };
    // const res = await thicknessAndLayOutJudgeApi.findOrderThkAlertBaseInfo(params);
    // console.log('查询曲线参数:', params);
    // console.log('查询曲线响应:', res.data);

    // // 使用接口返回 exthkSet 设置中线、上限、下限
    // if (res?.data?.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
    //   const exthkSet = Number(res.data.data[0].exthkSet);
    //   if (!Number.isNaN(exthkSet)) {
    //     nextCoilMidline.value = exthkSet; // 中线
    //   }
    // }

    // // 更新图表
    // updateCharts();

    const params1: any = {
      condition: {
        entid: filterParams.value.entryCoilNo || "",
        steelgrade: filterParams.value.steelGrade || "",
        widthClass: filterParams.value.width || "",
        orderThick: filterParams.value.thickness || "",
        orderCustCode: filterParams.value.customerCode || "",
        dbegin: filterParams.value.startTime || "",
        dend: filterParams.value.endTime || "",
        // 如果后续恢复厚度设定值下拉框，可一并传参：
        // exthkSet: filterParams.value.thicknessSetting || "",
      }
    };
    // 重置实时曲线，避免首次查询没有刷新
    currentThkData.value = [];

    const res1 = await thicknessAndLayOutJudgeApi.findOrderThkAlertData(params1);
    if (res1?.data?.data && Array.isArray(res1.data.data) && res1.data.data.length > 0) {
      // 取第一个可用 extid 获取实时厚度曲线
      for (let i = 0; i < res1.data.data.length; i++) {
        const extid = res1.data.data[i]?.extid;
        nextCoilThreshold.value.push(res1.data.data[i]?.exThkMin)
        nextCoilUpperline.value.push(res1.data.data[i]?.exThkMax)
        nextCoilMidline.value.push(res1.data.data[i]?.outMatThick)
        if (!extid) continue;
        const graphParam = {
          line: 'TCM2280',
          extid: [extid],
          kv: ["tcm_exs5_thk_act_avg"],
        };

        console.log('获取图表数据参数:', graphParam);
        const response = await historyApi.getgraphData(graphParam);
        const kv0 = response?.data?.data?.kv?.[0];
        if (kv0) {
          const raw = (kv0 as any).tcm_exs5_thk_act_avg;
          const values = Array.isArray(raw) ? raw : [raw];
          const numericValues = values
            .map((v: any) => Number(v))
            .filter((v: number) => !Number.isNaN(v));
          if (numericValues.length) {
            const startIndex = currentThkData.value.length;
            currentThkData.value.push(...numericValues);
            const endIndex = currentThkData.value.length - 1;
            const seg: CoilSegment = {
              coilNo: res1.data.data[i]?.entid || res1.data.data[i]?.coilNo || '',
              extid: extid ?? null,
              startIndex,
              endIndex,
              exThkMin: Number(res1.data.data[i]?.exThkMin ?? NaN) ?? null,
              exThkMax: Number(res1.data.data[i]?.exThkMax ?? NaN) ?? null,
              outMatThick: Number(res1.data.data[i]?.outMatThick ?? NaN) ?? null,
              seriesData: numericValues.slice(),
            };
            coilSegments.value.push(seg);
          }
        } else {
          console.warn('图表数据格式不正确或为空');
        }
      }
    }


    console.log('查询返回值:', res1);
    // 实时曲线数据准备完毕后再刷新一次，确保首次查询也可见
    updateCharts();
  } catch (error) {
    console.error('查询失败:', error);
  } finally {
    queryLoading.value = false;
  }
};

// 查询连退曲线数据
const handleContinuousRefundQuery = async () => {
  // 验证厚度和钢种
  if (!continuousRefundFilterParams.value.thickness || !continuousRefundFilterParams.value.thickness.trim()) {
    ElMessage.warning('请输入厚度');
    return;
  }
  if (!continuousRefundFilterParams.value.steelGrade || !continuousRefundFilterParams.value.steelGrade.trim()) {
    ElMessage.warning('请选择钢种');
    return;
  }
  
  continuousRefundQueryLoading.value = true;
  continuousRefundXData.value = [];
  continuousRefundYData.value = [];
  continuousRefundMidline.value = [];
  continuousRefundUpperline.value = [];
  continuousRefundThreshold.value = [];
  continuousRefundSegments.value = [];
  continuousRefundThinning.value = null;
  try {
    const params: any = {
      condition: {
        entid: continuousRefundFilterParams.value.entryCoilNo || "",
        steelgrade: continuousRefundFilterParams.value.steelGrade || "",
        orderThick: continuousRefundFilterParams.value.thickness || "",
        dbegin: continuousRefundFilterParams.value.startTime || "",
        dend: continuousRefundFilterParams.value.endTime || "",
      }
    };

    const res = await thicknessAndLayOutJudgeApi.findCal1630OrderThkAlertData(params);
    // 用于计算减薄量的数据：确保入口和出口厚度一一对应
    const entryThicknessList: number[] = [];
    const exitThicknessList: number[] = [];
    
    if (res?.data?.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
      for (let i = 0; i < res.data.data.length; i++) {
        const extid = res.data.data[i]?.extid;
        const exThkMin = res.data.data[i]?.exThkMin;
        const exThkMax = res.data.data[i]?.exThkMax;
        const outMatThick = res.data.data[i]?.orderThick;
        // 入口厚度：orderThick（订单厚度）
        const entryThick = res.data.data[i]?.inMatThk;
        
        if (!extid) {
          if (exThkMin != null || exThkMax != null || outMatThick != null) {
            if (continuousRefundYData.value.length === 0) {
              continuousRefundYData.value.push(0);
              continuousRefundThreshold.value.push(exThkMin);
              continuousRefundUpperline.value.push(exThkMax);
              continuousRefundMidline.value.push(outMatThick);
            }
          }
          continue;
        }
        const graphParam = {
          line: 'CAL1630',
          extid: [extid],
          kv: ["cal_ex_thk_guage_avg"],
        };

        console.log('获取连退图表数据参数:', graphParam);
        const response = await historyApi.getgraphData(graphParam);
        const kv0 = response?.data?.data?.kv?.[0];
        if (kv0) {
          const raw = (kv0 as any).cal_ex_thk_guage_avg;
          const values = Array.isArray(raw) ? raw : [raw];
          const numericValues = values
            .map((v: any) => Number(v))
            .filter((v: number) => !Number.isNaN(v));
          if (numericValues.length > 0) {
            // 计算该卷的平均出口厚度
            const avgExitThick = numericValues.reduce((sum, v) => sum + v, 0) / numericValues.length;
            exitThicknessList.push(avgExitThick);
            
            // 只有当成功获取出口厚度时，才将对应的入口厚度加入列表
            if (entryThick != null && !Number.isNaN(Number(entryThick))) {
              entryThicknessList.push(Number(entryThick));
            }
            
            const startIndex = continuousRefundYData.value.length;
            continuousRefundYData.value.push(...numericValues);
            const endIndex = continuousRefundYData.value.length - 1;
            continuousRefundThreshold.value.push(...new Array(numericValues.length).fill(exThkMin));
            continuousRefundUpperline.value.push(...new Array(numericValues.length).fill(exThkMax));
            continuousRefundMidline.value.push(...new Array(numericValues.length).fill(outMatThick));
            const seg: CoilSegment = {
              coilNo: res.data.data[i]?.entid || res.data.data[i]?.coilNo || '',
              extid: extid ?? null,
              startIndex,
              endIndex,
              exThkMin: Number(exThkMin ?? NaN) ?? null,
              exThkMax: Number(exThkMax ?? NaN) ?? null,
              outMatThick: Number(outMatThick ?? NaN) ?? null,
              seriesData: numericValues.slice(),
            };
            continuousRefundSegments.value.push(seg);
          }
        } else {
          console.warn('连退图表数据格式不正确或为空');
        }
      }
      if (continuousRefundYData.value.length) {
        continuousRefundXData.value = Array.from({ length: continuousRefundYData.value.length }, (_, i) => i + 1);
      }
      
      // 计算减薄量：平均出口厚度 - 平均入口厚度
      if (entryThicknessList.length > 0 && exitThicknessList.length > 0 && entryThicknessList.length === exitThicknessList.length) {
        const avgEntryThick = entryThicknessList.reduce((sum, v) => sum + v, 0) / entryThicknessList.length;
        const avgExitThick = exitThicknessList.reduce((sum, v) => sum + v, 0) / exitThicknessList.length;
        continuousRefundThinning.value = avgExitThick - avgEntryThick;
      }
    }
    updateCharts();
    if (continuousRefundChartInstance && continuousRefundYData.value.length > 0) {
      setTimeout(() => {
        initContinuousRefundChart();
      }, 100);
    }
  } catch (error) {
    console.error('连退查询失败:', error);
  } finally {
    continuousRefundQueryLoading.value = false;
  }
};

// 查询镀锌曲线数据
const handleGalvanizingQuery = async () => {
  // 验证厚度和钢种
  if (!galvanizingFilterParams.value.thickness || !galvanizingFilterParams.value.thickness.trim()) {
    ElMessage.warning('请输入厚度');
    return;
  }
  if (!galvanizingFilterParams.value.steelGrade || !galvanizingFilterParams.value.steelGrade.trim()) {
    ElMessage.warning('请选择钢种');
    return;
  }
  
  galvanizingQueryLoading.value = true;
  galvanizingXData.value = [];
  galvanizingYData.value = [];
  galvanizingMidline.value = [];
  galvanizingUpperline.value = [];
  galvanizingThreshold.value = [];
  galvanizingSegments.value = [];
  galvanizingThinning.value = null;
  try {
    const params: any = {
      condition: {
        entid: galvanizingFilterParams.value.entryCoilNo || "",
        steelgrade: galvanizingFilterParams.value.steelGrade || "",
        orderThick: galvanizingFilterParams.value.thickness || "",
        dbegin: galvanizingFilterParams.value.startTime || "",
        dend: galvanizingFilterParams.value.endTime || "",
      }
    };

    const res = await thicknessAndLayOutJudgeApi.findCGLOrderThkAlertData(params);
    // 用于计算减薄量的数据：确保入口和出口厚度一一对应
    const entryThicknessList: number[] = [];
    const exitThicknessList: number[] = [];
    const topZncoatThkList: number[] = [];
    const botZncoatThkList: number[] = [];
    
    if (res?.data?.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
      for (let i = 0; i < res.data.data.length; i++) {
        const extid = res.data.data[i]?.extid;
        const exThkMin = res.data.data[i]?.exThkMin;
        const exThkMax = res.data.data[i]?.exThkMax;
        const outMatThick = res.data.data[i]?.orderThick;
        // 入口厚度：orderThick（订单厚度）
        const entryThick = res.data.data[i]?.inMat1Thick;
        const topZncoatThk=res.data.data[i]?.topZncoatWt;
        const botZncoatThk=res.data.data[i]?.botZncoatWt;
        
        if (!extid) {
          if (exThkMin != null || exThkMax != null || outMatThick != null) {
            if (galvanizingYData.value.length === 0) {
              galvanizingYData.value.push(0);
              galvanizingThreshold.value.push(exThkMin);
              galvanizingUpperline.value.push(exThkMax);
              galvanizingMidline.value.push(outMatThick);
            }
          }
          continue;
        }
        const graphParam = {
          line: 'CGL1870',
          extid: [extid],
          kv: ["cgl_ex_gauge thk_avg"],
        };

        console.log('获取镀锌图表数据参数:', graphParam);
        const response = await historyApi.getgraphData(graphParam);
        const kv0 = response?.data?.data?.kv?.[0];
        if (kv0) {
          const raw = (kv0 as any)['cgl_ex_gauge thk_avg'];
          const values = Array.isArray(raw) ? raw : [raw];
          const numericValues = values
            .map((v: any) => Number(v))
            .filter((v: number) => !Number.isNaN(v));
          console.log(`镀锌第${i + 1}卷数据量:`, numericValues.length);
          if (numericValues.length) {
            // 计算该卷的平均出口厚度
            const avgExitThick = numericValues.reduce((sum, v) => sum + v, 0) / numericValues.length;
            exitThicknessList.push(avgExitThick);
            
            // 只有当成功获取出口厚度时，才将对应的入口厚度加入列表
            if (entryThick != null && !Number.isNaN(Number(entryThick))) {
              entryThicknessList.push(Number(entryThick));
            }

            if (topZncoatThk != null && !Number.isNaN(Number(topZncoatThk))) {
              topZncoatThkList.push(Number(topZncoatThk));
            }

            if (botZncoatThk != null && !Number.isNaN(Number(botZncoatThk))) {
              botZncoatThkList.push(Number(botZncoatThk));
            }
            
            const startIndex = galvanizingYData.value.length;
            galvanizingYData.value.push(...numericValues);
            const endIndex = galvanizingYData.value.length - 1;
            galvanizingThreshold.value.push(...new Array(numericValues.length).fill(exThkMin));
            galvanizingUpperline.value.push(...new Array(numericValues.length).fill(exThkMax));
            galvanizingMidline.value.push(...new Array(numericValues.length).fill(outMatThick));
            const seg: CoilSegment = {
              coilNo: res.data.data[i]?.entid || res.data.data[i]?.coilNo || '',
              extid: extid ?? null,
              startIndex,
              endIndex,
              exThkMin: Number(exThkMin ?? NaN) ?? null,
              exThkMax: Number(exThkMax ?? NaN) ?? null,
              outMatThick: Number(outMatThick ?? NaN) ?? null,
              seriesData: numericValues.slice(),
            };
            galvanizingSegments.value.push(seg);
          }
        } else {
          console.warn('镀锌图表数据格式不正确或为空', kv0);
        }
      }
      if (galvanizingYData.value.length) {
        galvanizingXData.value = Array.from({ length: galvanizingYData.value.length }, (_, i) => i + 1);
      }
      
      // 计算减薄量：平均出口厚度 - 平均入口厚度
      if (entryThicknessList.length > 0 && exitThicknessList.length > 0 && entryThicknessList.length === exitThicknessList.length) {
        const avgEntryThick = entryThicknessList.reduce((sum, v) => sum + v, 0) / entryThicknessList.length;
        const avgExitThick = exitThicknessList.reduce((sum, v) => sum + v, 0) / exitThicknessList.length;

        const avgTopZncoatWT = topZncoatThkList.reduce((sum, v) => sum + v, 0) / topZncoatThkList.length;
        const avgBotZncoatWt = botZncoatThkList.reduce((sum, v) => sum + v, 0) / botZncoatThkList.length;
        const avgZncoatThk=(avgTopZncoatWT+avgBotZncoatWt)/7.14/1000
        console.log("avgZncoatThk"+avgZncoatThk)

        galvanizingThinning.value = avgExitThick - avgEntryThick+avgZncoatThk;
      }
    }
    console.log('镀锌查询完成 - 数据统计:', {
      totalDataPoints: galvanizingYData.value.length,
      segments: galvanizingSegments.value.length,
      xDataLength: galvanizingXData.value.length,
      yDataLength: galvanizingYData.value.length,
      midlineLength: galvanizingMidline.value.length,
      upperlineLength: galvanizingUpperline.value.length,
      thresholdLength: galvanizingThreshold.value.length
    });
    // 数据加载完成后，重新初始化图表
    if (galvanizingYData.value.length > 0) {
      setTimeout(() => {
        console.log('开始初始化镀锌图表');
        initGalvanizingChart();
      }, 100);
    } else {
      console.warn('镀锌查询完成，但没有数据');
      // 如果没有数据，销毁现有实例
      if (galvanizingChartInstance) {
        galvanizingChartInstance.dispose();
        galvanizingChartInstance = null;
      }
    }
  } catch (error) {
    console.error('镀锌查询失败:', error);
  } finally {
    galvanizingQueryLoading.value = false;
  }
};

// 窗口大小变化处理
const handleResize = () => {
  nextCoilChartInstance?.resize();
  currentCoilChartInstance?.resize();
  dialogChartInstance?.resize();
  continuousRefundChartInstance?.resize();
  galvanizingChartInstance?.resize();
};

onMounted(() => {
  fetchData();
  setTimeout(() => {
    initNextCoilChart();
    initCurrentCoilChart();
    initContinuousRefundChart();
    initGalvanizingChart();
  }, 100);
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  nextCoilChartInstance?.dispose();
  currentCoilChartInstance?.dispose();
  dialogChartInstance?.dispose();
  continuousRefundChartInstance?.dispose();
  galvanizingChartInstance?.dispose();
});
</script>

<style lang="less" scoped>
.order-alert-container {
  width: 100%;
  height: 100vh;
  background: #0a1629;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  .header-title {
    text-align: center;
    color: #fff;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    padding: 10px 0;
  }

  .charts-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
    height: calc(100vh - 100px);

    .chart-panel {
      flex: 1;
      background: #0f2142;
      border-radius: 4px;
      padding: 15px;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .panel-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
        position: relative;

        .voice-alarm {
          display: flex;
          align-items: center;
          gap: 10px;

          .voice-label {
            color: #fff;
            font-size: 14px;
          }
        }

        .coil-info {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);

          .coil-number {
            color: #fff;
            font-size: 16px;
            font-weight: bold;
          }
        }

        .unit-label {
          color: #fff;
          font-size: 12px;
          margin-left: auto;
        }
      }

      .filter-section {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 15px;
        padding: 10px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 4px;
        flex-wrap: wrap;

        .filter-item {
          display: flex;
          align-items: center;
          gap: 1px;
          .filter-label {
            color: #fff;
            font-size: 14px;
            white-space: nowrap;
          }

          .filter-input {
            width: 100px;
          }

          .filter-select {
            width: 100px;
          }

        }
      }

      .filter-section-single-row {
        flex-wrap: nowrap;
        overflow-x: auto;
        
        .filter-item {
          flex-shrink: 0;
        }
      }

      .thinning-display {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 15px;
        padding: 8px 15px;
        background: rgba(255, 255, 255, 0.08);
        border-radius: 4px;
        border-left: 3px solid #409eff;

        .thinning-label {
          color: #fff;
          font-size: 14px;
          font-weight: bold;
        }

        .thinning-value {
          color: #409eff;
          font-size: 16px;
          font-weight: bold;
        }
      }

      // Element Plus组件样式覆盖
      :deep(.el-input__inner),
      :deep(.el-input__wrapper) {
        background-color: rgba(255, 255, 255, 0.1);
        border-color: rgba(255, 255, 255, 0.2);
        color: #fff;

        &::placeholder {
          color: rgba(255, 255, 255, 0.5);
        }
      }

      :deep(.el-select) {
        .el-input__inner {
          background-color: rgba(255, 255, 255, 0.1);
          border-color: rgba(255, 255, 255, 0.2);
          color: #fff;
        }
      }

      :deep(.el-select-dropdown) {
        background-color: #0f2142;
        border-color: rgba(255, 255, 255, 0.2);

        .el-select-dropdown__item {
          color: #fff;

          &:hover {
            background-color: rgba(255, 255, 255, 0.1);
          }

          &.selected {
            color: #409eff;
            background-color: rgba(64, 158, 255, 0.1);
          }
        }
      }

      .chart-wrapper {
        flex: 1;
        position: relative;
        min-height: 0;

        .chart {
          width: 100%;
          height: 100%;
        }

        .threshold-label {
          position: absolute;
          bottom: 10px;
          left: 50%;
          transform: translateX(-50%);
          display: flex;
          align-items: center;
          gap: 10px;

          .threshold-text {
            color: #ff0000;
            font-size: 14px;
            font-weight: bold;
          }

          .arrow {
            color: #ff0000;
            font-size: 16px;
            font-weight: bold;
          }
        }
      }
    }

    .bottom-charts {
      flex: 1;
      display: flex;
      gap: 20px;
      min-height: 0;

      .chart-panel {
        flex: 1;
      }
    }

    .left-panel {
      .threshold-label {
        .arrow {
          display: block;
        }
      }
    }

    .right-panel {
      .threshold-label {
        .arrow {
          display: none;
        }
      }
    }
  }
}

.dialog-chart-wrapper {
  width: 100%;
  height: 60vh;
  .chart {
    width: 100%;
    height: 100%;
  }
}

/* 弹窗白色主题，显示清晰的坐标轴与文字 */
:deep(.thk-dialog) {
  .el-dialog {
    background: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.08);
  }
  .el-dialog__header {
    color: #333;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    margin-right: 0;
  }
  .el-dialog__title {
    color: #333;
  }
  .el-dialog__headerbtn .el-dialog__close {
    color: rgba(0, 0, 0, 0.6);
  }
  .el-dialog__body {
    background: #ffffff;
    color: #333;
    padding: 0 20px 20px 20px;
  }
  .el-dialog__footer {
    border-top: 1px solid rgba(0, 0, 0, 0.05);
  }
}
</style>